package com.chcit.share.generator.controller;/**
 * <Description> <br>
 *
 * @author liuyang
 * @version 1.0
 * @createDate 2019/04/23 15:15
 * @see com.chcit.share.generator.controller
 */

import com.alibaba.fastjson.JSONArray;
import com.chcit.share.admin.core.http.HttpResult;
import com.chcit.share.dbms.vo.ConnParam;
import com.chcit.share.generator.config.GeneratorProperties;
import com.chcit.share.generator.service.GenerateService;
import com.chcit.share.generator.service.TemplateService;
import com.chcit.share.generator.utils.CodeGenUtil;
import com.chcit.share.generator.vo.GenerateModel;
import com.chcit.share.generator.vo.TableModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 *
 *@description:
 *@author: liuyang
 *@time: 2019/4/23 15:15
 *
 */
@RestController
@RequestMapping("")
public class GenerateController {

    @Autowired
    GenerateService generatorService;
    @Autowired
    private TemplateService templateService;
    @Autowired
    private GeneratorProperties generatorProperties;

    @PostMapping("/testConnection")
    public HttpResult testConnection(@RequestBody ConnParam connParam) {
        boolean success = generatorService.testConnection(connParam);
        if(success) {
            return HttpResult.ok(generatorService.testConnection(connParam));
        }
        return HttpResult.error("连接失败,请检查数据库及连接。");
    }

    @PostMapping("/getTables")
    public HttpResult getTables(@RequestBody ConnParam connParam) {
        return HttpResult.ok(generatorService.getTables(connParam));
    }

    @PostMapping("/getGenerateModel")
    public HttpResult getGenerateModel(@RequestBody GenerateModel generateModel) {
        return HttpResult.ok(generatorService.getGenerateModel(generateModel));
    }

    @PostMapping("/generateModels")
    public HttpResult generateModels(@RequestBody GenerateModel generateModel) throws Exception {
        return HttpResult.ok(generatorService.generateModels(generateModel));
    }

    @RequestMapping(value = "/genCode")
    public HttpResult genCode(@RequestBody GenerateModel model,
                         HttpServletRequest req, HttpServletResponse res) {

        JSONArray fileList  = new JSONArray();
        for (TableModel t : model.getTableModels()) {

            fileList.add(CodeGenUtil.codeGen(model.getGenerationEntity(),t,model.getTemplateModels()));
        }
        return HttpResult.ok(fileList);
    }

}
